package cn.fldong.service.impl;

import cn.fldong.dao.UserDAO;
import cn.fldong.dao.impl.UserDAOImpl;
import cn.fldong.model.User;
import cn.fldong.service.UserService;
import java.sql.SQLException;
import java.util.List;

/**
 * 用户服务实现类
 */
public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public User login(String username, String password) throws SQLException {
        // 获取用户信息
        User user = userDAO.findUserByUsername(username);
        
        // 验证用户存在且密码正确
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        
        return null;
    }

    @Override
    public boolean addUser(User user) throws SQLException {
        return userDAO.addUser(user);
    }

    @Override
    public User getUserById(int userId) throws SQLException {
        String obj=String.valueOf(userId);
        return userDAO.findUserById(obj);
    }

    @Override
    public User getUserByUsername(String username) throws SQLException {
        return userDAO.findUserByUsername(username);
    }

    @Override
    public boolean updateUser(User user) throws SQLException {
        return userDAO.updateUser(user);
    }

    @Override
    public boolean deleteUser(int userId) throws SQLException {
        return userDAO.deleteUser(userId);
    }

    @Override
    public List<User> getAllUsers() throws SQLException {
        return userDAO.findAllUsers();
    }

    @Override
    public boolean usernameExists(String username) throws SQLException {
        return userDAO.usernameExists(username);
    }

    @Override
    public boolean changePassword(int userId, String oldPassword, String newPassword) throws SQLException {
        String obj=String.valueOf(userId);
        // 先验证旧密码是否正确
        User user = userDAO.findUserById(obj);
        if (user != null && user.getPassword().equals(oldPassword)) {
            // 旧密码正确，更新密码
            user.setPassword(newPassword);
            return userDAO.updateUser(user);
        }
        return false;
    }

    @Override
    public boolean updateUserStatus(int userId, String status) throws SQLException {
        String obj=String.valueOf(userId);
        User user = userDAO.findUserById(obj);
        if (user != null) {
            user.setStatus(status);
            return userDAO.updateUser(user);
        }
        return false;
    }
}